﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LimitedScopeTrader.Data.StocksDataSetTableAdapters;
using LimitedScopeTrader.Data;

namespace LimitedScopeTrader
{
    /// <summary>
    /// This is the form with which the user logs onto the application. 
    /// </summary>
    public partial class frmLogon : LSTFormBase
    {
        
        public frmLogon()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Button click event handler to allow the user to log into the application
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            string userName = this.txtUserName.Text;
            string pswd = this.txtPassword.Text;

            // Don't even bother hitting the database if they didn't enter anything
            if (string.IsNullOrEmpty(userName))
            {
                MessageBox.Show(ApplicationConstants.INVALID_CREDENTIALS_ERROR, ApplicationConstants.MSGBOX_TITLE);
                return;
            }
            if (string.IsNullOrEmpty(pswd))
            {
                MessageBox.Show(ApplicationConstants.INVALID_CREDENTIALS_ERROR, ApplicationConstants.MSGBOX_TITLE);
                return;
            }

            DoLogon(userName, pswd);
            
        }

        /// <summary>
        /// Performs the actual logon to the application
        /// </summary>
        /// <param name="userName">User Name</param>
        /// <param name="pswd">Password</param>
        private void DoLogon(string userName, string pswd)
        {
            // Check the username and password in the database and log them in
            // if we find a match
            StocksDataSet.AccountsRow userAccount = this.businessLayer.GetAccountData(userName, pswd);

            // If logged in successfully, show the main form and close this one
            if (userAccount != null)
            {
                // Set up the application user credentials
                LSTApplication.User = userAccount;

                // Display the main data entry form
                frmMain main = new frmMain();
                main.MdiParent = this.MdiParent;
                main.Show();

                // close this screen
                this.Close();
            }
            else
            {
                // Make sure the user credentials are cleared
                LSTApplication.User = null;
                MessageBox.Show(ApplicationConstants.INVALID_CREDENTIALS_ERROR, ApplicationConstants.MSGBOX_TITLE);
            }
        }
    }
}
